package vn.bus.bk;

import java.util.ArrayList;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.MenuItem;


import vn.bus.bk.object.BusInfo;
import vn.bus.bk.other.AnimationEditText;
import vn.bus.bk.other.Convert;
import vn.bus.bk.adapter.ListBusAdapter;
import vn.bus.bk.adapter.SQLiteAdapter;
import vn.bus.bk.dialog.DialogMessage;
import android.app.ProgressDialog;
import android.content.Context;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ListView;

public class SearchByPlace extends SherlockFragmentActivity {

    private String searchPlace = null;
    AutoCompleteTextView place;
    Button findBt;
    private ListView myListViewBus;
    private ListBusAdapter myAdapter;
    private SQLiteAdapter mySQLAdapter;
    public Cursor mCursor;
    public int iNumber, iGoBus, iBackBus, iName, iTimeStartBus, iTimeEndBus,
	    iFrequency, iValue, iOrdinateGo, iOrdinateBack;
    private String[] columns;
    public ArrayList<BusInfo> myListBus;
    public ArrayAdapter<String> adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
	// TODO Auto-generated method stub
	super.onCreate(savedInstanceState);
	setContentView(R.layout.searchbyplace);
	columns = getResources().getStringArray(R.array.arrayColumn);
	setTitle(getString(R.string.menu_item_2));
	getSupportActionBar().setDisplayHomeAsUpEnabled(true);
	getSupportActionBar().setHomeButtonEnabled(true);
	init();
	getWindow().setSoftInputMode(
		WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
	setTitle(getString(R.string.menu_item_2));
	place = (AutoCompleteTextView) findViewById(R.id.autoTextPlace);
	createAdapter();
	place.setAdapter(adapter);
	findBt = (Button) findViewById(R.id.find_button);
	findBt.setOnClickListener(find_click);

    }

    private OnClickListener find_click = new OnClickListener() {

	public void onClick(View v) {
	    // TODO Auto-generated method stub
	    searchPlace = place.getText().toString();
	    if (searchPlace.trim().length() != 0) {

		FindAsynTask taskFind = new FindAsynTask(SearchByPlace.this);
		taskFind.execute("find");
	    } else {
		// DialogMessage dialog = new DialogMessage(SearchByPlace.this,
		// getString(R.string.not_enough_data_input));
		// dialog.show(false);
		showAnimation();
	    }

	}
    };

    private void showAnimation() {
//	Animation shake = AnimationUtils.loadAnimation(this, R.anim.shake);
//	place.startAnimation(shake);
	AnimationEditText.shakeAnimation(this, place);
    }

    private void init() {
	myListViewBus = (ListView) findViewById(R.id.listBusPlace);
    }

    private void createAdapter() {
	String[] array;

	if (SQLiteAdapter.getNameCity(this) == 1) {
	    array = getResources().getStringArray(R.array.arrayPlaceHN);
	} else {
	    array = getResources().getStringArray(R.array.arrayPlaceHCM);
	}
	adapter = new ArrayAdapter<String>(this,
		android.R.layout.simple_dropdown_item_1line, array);
    }

    public boolean loadListFromDatabase() {
	myListBus = new ArrayList<BusInfo>();
	mySQLAdapter = new SQLiteAdapter(this);
	try {
	    mySQLAdapter.close();
	    mySQLAdapter.copyDataBase();
	    mySQLAdapter.openDataBase();

	} catch (Exception e) {
	    // TODO Auto-generated catch block
	    Log.i("DATABASE", "Cannot connect to database");
	}
	try {

	    mCursor = mySQLAdapter.rawAll();
	    mCursor.moveToFirst();
	    initialzeIndex();

	    do {
		if (searchString(searchPlace, mCursor.getString(iGoBus))) {
		    myListBus.add(new BusInfo(mCursor.getInt(iNumber), mCursor
			    .getString(iName), mCursor.getString(iGoBus),
			    mCursor.getString(iBackBus), mCursor
				    .getString(iTimeStartBus), mCursor
				    .getString(iTimeEndBus), mCursor
				    .getString(iFrequency), mCursor
				    .getString(iValue), mCursor
				    .getString(iOrdinateGo), mCursor
				    .getString(iOrdinateBack)));

		}
		mCursor.moveToNext();
	    } while (!mCursor.isAfterLast());

	} catch (Exception e) {
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	}
	mySQLAdapter.close();
	if (myListBus.size() != 0) {
	    return true;
	} else {
	    return false;
	}

    }

    private void initialzeIndex() {
	// TODO Auto-generated method stub
	iNumber = mCursor.getColumnIndex(columns[0]);
	iGoBus = mCursor.getColumnIndex(columns[1]);
	iBackBus = mCursor.getColumnIndex(columns[2]);
	iName = mCursor.getColumnIndex(columns[3]);
	iTimeStartBus = mCursor.getColumnIndex(columns[4]);
	iTimeEndBus = mCursor.getColumnIndex(columns[5]);
	iFrequency = mCursor.getColumnIndex(columns[6]);
	iValue = mCursor.getColumnIndex(columns[7]);
	iOrdinateGo = mCursor.getColumnIndex(columns[8]);
	iOrdinateBack = mCursor.getColumnIndex(columns[8]);
    }

    private void setup() {
	myAdapter = new ListBusAdapter(this, myListBus);
	myListViewBus.setAdapter(myAdapter);
    }

    private boolean searchString(String input, String fromString) {
	input = input.toLowerCase();
	input = Convert.convert(input);
	input = input.trim();

	fromString = fromString.toLowerCase();
	fromString = Convert.convertRoute(fromString);
	return check(input, fromString);
    }

    private boolean check(String input, String output) {
	int n = input.length();
	int m = output.length();
	for (int i = 0; i < m - n + 1; i++) {
	    String s = output.substring(i, i + n);
	    if (s.equals(input))
		return true;
	}
	return false;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
	// TODO Auto-generated method stub
	if (item.getItemId() == android.R.id.home) {
	    finish();
	}
	return super.onOptionsItemSelected(item);
    }

    public class FindAsynTask extends AsyncTask<String, Integer, String> {

	private Context mContext;
	private boolean isFinded;
	private ProgressDialog dialog;

	public FindAsynTask(Context context) {
	    this.mContext = context;
	    Log.i("TAG", "Contructor");
	}

	@Override
	protected void onPreExecute() {
	    // TODO Auto-generated method stub
	    super.onPreExecute();
	    this.dialog = new ProgressDialog(mContext);
	    this.dialog.setMessage("Loading.....");
	    this.dialog.show();

	}

	@Override
	protected String doInBackground(String... arg0) {
	    // TODO Auto-generated method stub
	    isFinded = loadListFromDatabase();
	    return null;
	}

	@Override
	protected void onPostExecute(String result) {
	    // TODO Auto-generated method stub
	    super.onPostExecute(result);
	    if (dialog.isShowing()) {
		dialog.dismiss();
	    }
	    if (isFinded) {
		setup();
	    } else {
		DialogMessage dialogmessage = new DialogMessage(mContext,
			getString(R.string.not_find_place));
		dialogmessage.show(false);
	    }

	}

    }

}
